<?php

namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\SysUser as UserModel;
use think\Exception;

class SysUser
{
    public $userObj = null;
    public function __construct()
    {
        $this->userObj = new UserModel();
    }
    public function login($data){
        //需要判断表 是否有 用户记录 user_name
        //生成token
        $user = $this->userObj->getUserByUsername($data['username']);
        $sysLogininfor = new SysLogininfor();
        if(empty($user)){
            $sysLogininfor->addLogininfor('不存在该用户',$data['username'],1);
            throw new Exception("不存在该用户");
        }
        //判断密码是否正确
        if($user['password'] != md5(config("redis.password_salt").$data['password'])){
            $sysLogininfor->addLogininfor('密码错误',$data['username'],1);
            throw new Exception("密码错误");
        }
        //需要记录信息到mysql表中
        $updateData = [
            'login_date'=>date("Y-m-d H:i:s",time()),
            'login_ip'=>request()->ip(),
            'update_time'=>date("Y-m-d H:i:s",time()),
        ];
        $res = $this->userObj->updateById($user['user_id'],$updateData);
        if(empty($res)){
            throw new Exception("登录失败");
        }

        $userId     = $user->user_id;
        $username   = $user->user_name;
        $dept_id    = $user->dept_id;
        $token = Str::getLoginToken($data['username']);
        $redisData = [
            "id"=>$userId,
            "username"=>$username,
            "dept_id"=>$dept_id,
        ];
        $res = cache(config("redis.token_pre").$token,$redisData,Time::userLoginExpiresTime());
        return $res ? ["token"=>$token,"username"=>$username] : false;
    }

    //查询用户列表
    public function getNormalUser($where,$field,$limit,$page){
        $userData = $this->userObj->getNormalUserList($where,$field,$limit,$page);
        if(!$userData){
            return [];
        }
        $userData = $userData->toArray();
        return $userData;
    }

    /**
     * 根据主键id更新用户状态
     * @param $id
     * @param $data
     * @return bool
     */
    public function changeStatusUser($userId,$status){
        $userId = intval($userId);
        if(empty($userId)){
            return false;
        }
        //根据$userId去数据库查询这条记录
        $postNameResult = $this->getUserById($userId);
        if($postNameResult){
            if($postNameResult['user_name'] == "admin"){
                throw new \think\Exception("不允许操作超级管理员用户");
            }
        }
        return $this->userObj->changeStatusUserModel($userId,$status);
    }

    /**
     * 根据主键id重置用户密码
     * @param $id
     * @param $data
     * @return bool
     */
    public function resetPwdUser($userId,$password){
        $userId = intval($userId);
        if(empty($userId)){
            return false;
        }
        return $this->userObj->resetPwdUserModel($userId,$password);
    }

    //添加用户
    public function addUser($data){
        //根据$user_name去数据库查询是否存在这条记录
        $postNameResult = $this->getUserByName($data['user_name']);
        if($postNameResult){
            throw new \think\Exception("该用户名称已经存在请重新设置");
        }
        try {
            $this->userObj->save($data);
        }catch (\Exception $e){
            throw new \think\Exception($e->getMessage());
        }
        return $this->userObj->id;
    }

    public function getUserByName($user_name,$user_id = ''){
        $user = $this->userObj->getUserByNameFind($user_name,$user_id);
        if(!$user){
            return [];
        }
        return $user->toArray();
    }

    //根据$id,去数据库查询是否存在这条记录
    public function getUserById($id){
        $user = $this->userObj->getUserByIdFind($id);
        if(!$user){
            return [];
        }
        return $user->toArray();
    }

    /**
     * 根据主键id更新数据表中的数据
     * @param $id
     * @param $data
     * @return bool
     */
    public function updateById($id,$data,$falg = true){
        $id = intval($id);
        if(empty($id) || empty($data) || !is_array($data)){
            return false;
        }
        if($falg){
            //根据$user_name去数据库查询是否存在这条记录
            $postNameResult = $this->getUserByName($data['user_name'],$id);
            if($postNameResult){
                throw new \think\Exception("该用户名称已经存在请重新设置");
            }
        }
        return $this->userObj->updateUserById($id,$data);
    }

    //根据$ids数组，删除数据库记录delete
    public function DelUserIds($ids){
        $ids = explode(',', $ids);
        //根据$ids数组去数据库查询是否存在user_name = admin这条记录
        $postNameResult = $this->getUserByNameId($ids);
        if($postNameResult){
            throw new \think\Exception("当前用户不能删除");
        }

        //根据$ids去数据库查询是否存在这条记录
        $result = $this->userObj->DelUserIdsData($ids);
        return $result;
    }

    public function getUserByNameId($ids){
        $user = $this->userObj->getUserByNameIdFind($ids);
        if(!$user){
            return [];
        }
        return $user->toArray();
    }

    public function insertAllUser($data){
        try {
            $this->userObj->saveAll($data);
        }catch (\Exception $e){
            throw new \think\Exception($e->getMessage());
        }
        return $this->userObj->id;
    }
}
